package com.xrf;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.system.as.application.system.basics.user.service.UserService;
import com.system.as.application.system.common.CodeBusinessSystem;
import com.system.as.application.system.request.user.ReqLogin;
import com.system.core.common.EnumCode;
import com.system.core.common.ResultView;
import com.system.core.common.base.BaseController;
import com.system.core.tool.ToolCaptchaImage;
import com.system.core.tool.ToolMD5;
import com.system.core.tool.ToolRandom;
import com.system.core.tool.ToolRedis;
import io.system.annotations.Api;
import io.system.annotations.ApiOperation;

@RestController
@RequestMapping("/")
public class LoginController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    @Autowired
    private UserService userServiceImpl;
    
    @Autowired
    private ToolRedis redis;
    
    @RequestMapping(method = { RequestMethod.POST }, path = "/login")
    public ResultView login(@Valid @RequestBody ReqLogin model) {
        ResultView resultView = new ResultView();
        try {
            resultView = userServiceImpl.login(model.getUserName(), model.getPassword(), model.getFlag(), model.getCaptcha(), "0");
        } catch (Exception e) {
            resultView.setCode(EnumCode.ERROR_9999);
            resultView.setMsg(e.getMessage());
        }
        return resultView;
    }
    
    @RequestMapping(method = { RequestMethod.POST }, path = "/appLogin")
    public ResultView appLogin(@Valid @RequestBody ReqLogin model) {
        ResultView resultView = new ResultView();
        try {
            resultView = userServiceImpl.login(model.getUserName(), model.getPassword(), model.getFlag(), model.getCaptcha(), "1");
        } catch (Exception e) {
            resultView.setCode(EnumCode.ERROR_9999);
            resultView.setMsg(e.getMessage());
        }
        return resultView;
    }
    
    @GetMapping("/captchaImage")
    public void getCaptcha(HttpServletResponse response, String flag) {
        ByteArrayOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            String captchaCode = ToolCaptchaImage.generateTextCode(ToolCaptchaImage.TYPE_ALL_MIXED, 4, null);
            BufferedImage img = ToolCaptchaImage.generateImageCode(captchaCode, 100, 34, 3, true, Color.WHITE, Color.BLACK, Color.GRAY,
                    ToolCaptchaImage.FONT_TYPE_TIMES_NEW_ROMAN);
            redis.set(MessageFormat.format(CodeBusinessSystem.REDIS_CAPTCHA_KEY.getValue(), flag), captchaCode, 300L);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(img, "JPEG", outputStream);
            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment; filename=captcha.jpg");
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            bufferedOutputStream.write(outputStream.toByteArray());
            bufferedOutputStream.flush();
        } catch (IOException e) {
            logger.error("获取图片验证码失败", e);
        } finally {
            try {
                if (null != bufferedOutputStream) {
                    bufferedOutputStream.close();
                }
                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.warn("获取图片验证码，关闭文件流异常", e);
            }
        }
    }
    
    @GetMapping("/login-keys")
    public String selectAesKey(String flag) {
        String value = flag + ToolRandom.getStringByLen(3);
        redis.set(MessageFormat.format(CodeBusinessSystem.REDIS_AES_KEY.getValue(), flag), value, 300L);
        return value;
    }
    
    public static void main(String[] args) {
        System.out.println(ToolMD5.encryptPassword("123456", "sa"));
    }
}